package com.haiyi.software.entity;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.jivesoftware.smack.packet.DefaultPacketExtension;
import org.jivesoftware.smack.packet.Message;
import org.xmlpull.v1.XmlPullParser;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.haiyi.software.app.ActivityStandardImage;
import com.haiyi.software.app.HiChat;
import com.haiyi.software.app.ImagePagerActivity;
import com.haiyi.software.app.MainApplication;
import com.haiyi.software.app.R;
import com.haiyi.software.dao.ChatDAO;
import com.haiyi.software.tools.L;
import com.haiyi.software.tools.MyTools;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.ResponseHandlerInterface;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

public class EntityMsgImage extends EntityMsg {

	private String image;

	private String local_image_path;

	private String imageThumbSrc;

	private View chatImageView;

	private TextView textView_progress;

	private ImageView img_chat_image_left;

	MyTools mt = MyTools.getInstance();

	private DisplayImageOptions options;

	private ImageLoader imageLoader;

	public EntityMsgImage() {
		super();
		imageLoader = ImageLoader.getInstance();
		options = new DisplayImageOptions.Builder()
				.imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
				.showImageOnLoading(R.drawable.ic_launcher)
				.showImageForEmptyUri(R.drawable.ic_launcher).cacheOnDisk(true)
				.showImageOnFail(R.drawable.ic_launcher).cacheInMemory(true)
				.considerExifParams(true)
				.displayer(new RoundedBitmapDisplayer(10)).build();
	}

	public View getChatImageView() {
		return chatImageView;
	}

	public void setChatImageView(View chatImageView) {
		this.chatImageView = chatImageView;
	}

	public String getImageThumbSrc() {
		return imageThumbSrc;
	}

	public void setImageThumbSrc(String imageThumbSrc) {
		this.imageThumbSrc = imageThumbSrc;
	}

	public String getLocal_image_path() {
		return local_image_path;
	}

	public void setLocal_image_path(String local_image_path) {
		this.local_image_path = local_image_path;

	}

	public String getImage() {
		return image;
	}

	public void setImage(String image) {
		this.image = image;
	}

	public void imageShow() {

		if (chatImageView != null) {

			img_chat_image_left = (ImageView) chatImageView
					.findViewById(R.id.img_chat_image_left);

			textView_progress = (TextView) chatImageView
					.findViewById(R.id.textView_progress);

			if (local_image_path.length() == 0) {

				img_chat_image_left.setImageResource(R.drawable.imgclickload);

				img_chat_image_left.setOnClickListener(imgDownloadClick);

			} else {

				img_chat_image_left.setOnClickListener(imgShowBigClick);

				imageLoader.displayImage("file://" + local_image_path,
						img_chat_image_left, options);

			}
		}

	}

	private View.OnClickListener imgShowBigClick = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO 自动生成的方法存根

			// TODO 自动生成的方法存根
			EntityUserPhoto userPhoto = new EntityUserPhoto();

			userPhoto.setAttuid(image);

			userPhoto.setPhobig(local_image_path);

			userPhoto.setPhosmall("");

			startImagePagerActivity(userPhoto);

		}
	};

	private void startImagePagerActivity(EntityUserPhoto userPhoto) {

		Intent intent = new Intent();

		intent.setClass(context, ActivityStandardImage.class);

		intent.putExtra("image", userPhoto.getPhobig());

		context.startActivity(intent);
	}

	private View.OnClickListener imgDownloadClick = new View.OnClickListener() {

		@Override
		public void onClick(View v) {

			textView_progress.setVisibility(View.VISIBLE);
			textView_progress.setText("获取中...");

			ImgHandler getImagehandler = new ImgHandler();

			mt.downLoadFileByAttuid(image, getImagehandler);

		}
	};

	private class ImgHandler extends Handler {

		@Override
		public void handleMessage(android.os.Message msg) {
			// TODO 自动生成的方法存根
			super.handleMessage(msg);

			L.i("msg", msg.toString());

			JsonObject jsReturn = mt.getJsonDownloadReturn().getAsJsonObject();

			if (jsReturn.get("state").getAsString().equals("200")) {

				String big = jsReturn.get("body").getAsJsonArray().get(0)
						.getAsJsonObject().get("filesrc").getAsString();

				String server = MainApplication.getInstance().getResources()
						.getString(R.string.URL);

				imageDownload(server + big);
			}

		}

	}

	private void imageUpdateDBMessage(String imagePath) {

		int int_begin = allMessage.indexOf("<local_image_path>");

		int int_end = allMessage.indexOf("</local_image_path>");

		String allMsg1 = allMessage.substring(0, int_begin + 18);
		String allMsg2 = allMessage.substring(int_end, allMessage.length());

		String newMsg = allMsg1 + imagePath + allMsg2;

		ChatDAO.getInstence().changeNewMessageBody(messageID, newMsg);

	}

	private void imageDownload(String imgsrc) {

		AsyncHttpClient client = MainApplication.getInstance()
				.getAsyncHttpClient();

		String imageFileName = MainApplication.getInstance().getMineUserInfo()
				.getUid()
				+ "_d_" + System.currentTimeMillis() + ".jpg";

		String imageFileSrc = MainApplication.getInstance()
				.getAppImageDirectory() + "/" + imageFileName;

		File file = new File(imageFileSrc);

		client.setTimeout(600000);

		client.post(imgsrc, new FileAsyncHttpResponseHandler(file) {

			public void onProgress(int bytesWritten, int totalSize) {

				if (chatImageView != null) {

					textView_progress = (TextView) chatImageView
							.findViewById(R.id.textView_progress);

					L.i("%%%",
							(int) (Math.floor(bytesWritten * 100 / totalSize))
									+ "%");

					if (bytesWritten == totalSize) {
						textView_progress.setVisibility(View.GONE);
					} else {
						textView_progress.setVisibility(View.VISIBLE);

						textView_progress.setText((int) (Math
								.floor(bytesWritten * 100 / totalSize)) + "%");
					}
				}

			};

			@Override
			public void onSuccess(int statusCode, Header[] headers, File file) {

				imageLoader.displayImage("file://" + file.getPath(),
						img_chat_image_left, options);
				img_chat_image_left.setOnClickListener(imgShowBigClick);
				setLocal_image_path(file.getPath());
				imageUpdateDBMessage(file.getPath());
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, File file) {
				// TODO 自动生成的方法存根

			}
		});
	}

	private ResponseHandlerInterface imageDownloadResponseHandler = new AsyncHttpResponseHandler() {

		public void onProgress(int bytesWritten, int totalSize) {

			if (chatImageView != null) {

				textView_progress = (TextView) chatImageView
						.findViewById(R.id.textView_progress);

				Log.i("%%%", (int) (Math.floor(bytesWritten * 100 / totalSize))
						+ "%");

				if (bytesWritten == totalSize) {
					textView_progress.setVisibility(View.GONE);
				} else {
					textView_progress.setVisibility(View.VISIBLE);

					textView_progress.setText((int) (Math.floor(bytesWritten
							* 100 / totalSize))
							+ "%");
				}
			}

		};

		@Override
		public void onSuccess(int statusCode, Header[] headers,
				byte[] responseBody) {

			// 创建工厂对象
			BitmapFactory bitmapFactory = new BitmapFactory();
			// 工厂对象的decodeByteArray把字节转换成Bitmap对象
			Bitmap bitmap = bitmapFactory.decodeByteArray(responseBody, 0,
					responseBody.length);
			// 设置图片
			img_chat_image_left.setImageBitmap(bitmap);

		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] responseBody, Throwable error) {
			// TODO 自动生成的方法存根

		}
	};

	/**
	 * 上传图片
	 */
	public void imageUpload() {

		File imageFile = new File(local_image_path);

		if (imageFile.exists() && imageFile.length() > 0) {

			String uploadUrl = MainApplication.getInstance().getResources()
					.getString(R.string.URL)
					+ "upload.php";

			AsyncHttpClient client = new AsyncHttpClient();
			String contType = URLConnection
					.guessContentTypeFromName(local_image_path);

			RequestParams params = new RequestParams();
			params.put("args", getJsonArgs(imageFile));
			try {
				params.put("attfile", imageFile, contType);
				client.setTimeout(60000);
				client.post(uploadUrl, params, rpHandler);

			} catch (FileNotFoundException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}
	}

	private ResponseHandlerInterface rpHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onProgress(int bytesWritten, int totalSize) {
			// TODO 自动生成的方法存根
			super.onProgress(bytesWritten, totalSize);

			if (chatImageView != null) {

				textView_progress = (TextView) chatImageView
						.findViewById(R.id.textView_progress);

				if (bytesWritten == totalSize) {
					textView_progress.setVisibility(View.GONE);
				} else {
					textView_progress.setVisibility(View.VISIBLE);

					textView_progress.setText((int) (Math.floor(bytesWritten
							* 100 / totalSize))
							+ "%");
				}
			}

		}

		@Override
		public void onSuccess(int statusCode, Header[] headers,
				byte[] responseBody) {

			try {

				String str_jsonReturn = new String(responseBody, "UTF-8");

				Log.i("str_jsonReturn", str_jsonReturn);

				JsonParser parse = new JsonParser();

				JsonObject jsonReturnImage = parse.parse(str_jsonReturn)
						.getAsJsonObject();
				UploadImageSuccess(jsonReturnImage);

			} catch (UnsupportedEncodingException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] responseBody, Throwable error) {
			// TODO 自动生成的方法存根

		}
	};

	protected void UploadImageSuccess(JsonObject jsonReturnImage) {

		if (jsonReturnImage.get("state").getAsString().equals("200")) {

			String attuid = jsonReturnImage.get("body").getAsJsonObject()
					.get("attuid").getAsString();

			EntityMsgImage msg = new EntityMsgImage();

			msg.setyUID(yUID);
			msg.setBody("[图片]");
			msg.setImage(attuid);
			msg.setLocal_image_path(local_image_path);
			msg.setDatetime(MyTools.getInstance().getDateTimeNow());
			msg.setAllMessage(msg.getPacket().toXML());

			AddMyMessageToDB(msg, userFriend);

			EntityMsgImage msg2 = new EntityMsgImage();

			msg2.setyUID(userFriend.getUfID());
			msg2.setBody("[图片]");
			msg2.setImage(attuid);
			msg2.setLocal_image_path("");
			msg2.setDatetime(MyTools.getInstance().getDateTimeNow());

			sendXMPPMessage(msg2);

		}
	}

	private String getJsonArgs(File imageFile) {

		UserInfo myInfo = MainApplication.getInstance().getMineUserInfo();

		if (myInfo != null) {

			Map<String, Object> validator = new HashMap<String, Object>();

			validator.put("uid", myInfo.getUid());
			validator.put("uname", myInfo.getUname());
			validator.put("pwd", myInfo.getPwd());
			validator.put("uguid", myInfo.getUguid());

			Map<String, Object> body = new HashMap<String, Object>();

			body.put("typeid", 3);

			body.put("filedatasrc", imageFile.getPath());

			body.put("videolong", 0);

			body.put("md5id", MyTools.getMd5ByFile(imageFile));

			Map<String, Object> args = new HashMap<String, Object>();
			args.put("validator", validator);
			args.put("body", body);

			Gson gson = new Gson();
			String s = gson.toJson(args);

			Log.i("argsJson", s);
			return s;
		} else {
			return "";
		}

	}

	@Override
	public void setAllMessage(String allMessage) {

		this.allMessage = allMessage;

		InputStream xmlInStream = new ByteArrayInputStream(
				allMessage.getBytes());

		XmlPullParser pull = Xml.newPullParser();

		try {
			pull.setInput(xmlInStream, "utf-8");

			int type = pull.getEventType();

			while (type != XmlPullParser.END_DOCUMENT) {

				switch (type) {
				case XmlPullParser.START_DOCUMENT:
					// entMsg.setAllMessage(str_xml);
					break;
				case XmlPullParser.START_TAG:

					if ("message".equals(pull.getName())) {

						this.setMessageID(pull.getAttributeValue(null, "id"));

					} else if ("body".equals(pull.getName())) {

						this.setBody(pull.nextText());

					} else if ("uhead".equals(pull.getName())) {

						this.setUhead(pull.nextText());

					} else if ("name".equals(pull.getName())) {

						this.setName(pull.nextText());

					} else if ("image".equals(pull.getName())) {

						this.setImage(pull.nextText());

					} else if ("local_image_path".equals(pull.getName())) {

						this.setLocal_image_path(pull.nextText());

					} else if ("username".equals(pull.getName())) {

						this.setUsername(pull.nextText());

					}
					break;
				case XmlPullParser.END_DOCUMENT:

					break;
				}
				type = pull.next();

			}
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}

	@Override
	public Message getPacket() {

		UserInfo myInfo = MainApplication.getInstance().getMineUserInfo();

		String strServerIP = MainApplication.getInstance().getServerIP();

		String XMPPID = this.yUID + "@" + strServerIP + "/Android";

		Message msg = new Message(XMPPID, Message.Type.chat);

		DefaultPacketExtension DeExtension = new DefaultPacketExtension(
				"MyExtension", "jabber:client");

		DeExtension.setValue("name", myInfo.getUname());

		DeExtension.setValue("username", myInfo.getUsername());

		DeExtension.setValue("uhead", myInfo.getHeadSmall());

		DeExtension.setValue("image", this.image);

		DeExtension.setValue("local_image_path", this.local_image_path);

		msg.setBody(body);

		msg.addExtension(DeExtension);

		return msg;
	}

	@Override
	public int getMessageCategory() {
		// TODO 自动生成的方法存根
		return MESSAGECATEGORY_IMAGE;
	}

}
